from db_base import DatabaseManager, dbconfig


class DeviceManager:
    def __init__(self):
        # 初始化数据库连接
        self.db_manager = DatabaseManager(dbconfig)

    def __del__(self):
        # 确保资源释放
        self.db_manager.close()

    def delete_device(self, device_id):
        """删除设备数据库记录"""
        try:
            query = "DELETE FROM medical_devices WHERE device_id = %s"
            self.db_manager.execute_query(query, (device_id,), commit=True)
            return not (self.device_exists(device_id))
        except Exception as e:
            print(f"数据库删除设备失败: {e}")
            return False

    def add_new_device(self, device_id, device_type, status, location, calibration_date, therapist_id):
        """
        添加新设备到数据库
        返回:
            bool: 是否成功
        """
        try:
            query = """
                   INSERT INTO medical_devices 
                   (device_id, device_type, status, location, last_calibration, responsible_therapist)
                   VALUES (%s, %s, %s, %s, %s, %s)
                   """
            params = (
                device_id,
                device_type,
                status,
                location,
                calibration_date,
                therapist_id
            )
            self.db_manager.execute_query(query, params, commit=True)
            return self.device_exists(device_id)
        except Exception as e:
            print(f"数据库添加设备失败: {e}")
            return False

    def get_therapist_devices(self, therapist_id):
        """
        获取指定治疗师负责的所有设备
        参数:
            therapist_id: 治疗师ID
        返回:
            设备列表(字典组成的列表)，查询失败返回None
        """
        query = """
        SELECT 
            device_id, 
            device_type, 
            status, 
            location, 
            last_calibration,
            TIMESTAMPDIFF(DAY, last_calibration, CURDATE()) AS days_since_calibration
        FROM medical_devices
        WHERE responsible_therapist = %s
        ORDER BY status, device_type
        """
        try:
            return self.db_manager.execute_query(query, (therapist_id,))
        except Exception as e:
            print(f"查询治疗师设备失败: {e}")
            return None

    def update_device_status(self, device_id, new_status):
        """
        更新设备状态
        参数:
            device_id: 设备ID
            new_status: 新状态
        返回:
            成功返回True，失败返回False
        """
        query = """
        UPDATE medical_devices 
        SET status = %s 
        WHERE device_id = %s
        """
        try:
            self.db_manager.execute_query(query, (new_status, device_id), commit=True)
            return True
        except Exception as e:
            print(f"更新设备状态失败: {e}")
            return False

    def get_device_info(self, device_id):
        """
        获取设备详细信息
        参数:
            device_id: 设备ID
        返回:
            设备信息字典，未找到返回None
        """
        query = """
        SELECT 
            d.*,
            t.username AS therapist_name
        FROM medical_devices d
        LEFT JOIN users t ON d.responsible_therapist = t.user_id
        WHERE d.device_id = %s
        """
        try:
            result = self.db_manager.execute_query(query, (device_id,))
            return result[0] if result else None
        except Exception as e:
            print(f"获取设备信息失败: {e}")
            return None

    def update_device(self, device_id, new_status, new_location, updated_by):
        """
        更新设备信息到数据库
        参数:
            device_id: 设备ID
            new_status: 新状态(英文值)
            new_location: 新位置
            updated_by: 操作人ID
        返回:
            bool: 是否成功
        """
        try:
            query = """
                UPDATE medical_devices 
                SET 
                    status = %s,
                    location = %s,
                    last_calibration = NOW(),
                    responsible_therapist = %s
                WHERE device_id = %s
            """
            params = (
                new_status,
                new_location,
                updated_by,
                device_id
            )
            # 执行更新并返回影响的行数
            self.db_manager.execute_query(query, params, commit=True)
            return self.device_exists(device_id)
        except Exception as e:
            print(f"数据库更新设备失败: {e}")
            return False

    def device_exists(self, device_id):
        """
        检查设备是否存在
        参数:
            device_id: 设备ID
        返回:
            bool: 是否存在
        """
        try:
            query = "SELECT 1 FROM medical_devices WHERE device_id = %s"
            result = self.db_manager.execute_query(query, (device_id,))
            return bool(result)
        except Exception as e:
            print(f"检查设备存在性失败: {e}")
            return False
